<template>
  <div class="player_class">
    <!-- 歌曲封面头像 -->
    <PlayerCover :song="playList[currentIndex]"></PlayerCover>

    <!-- 歌词 -->
    <PlayerLyric class="player_lyric" v-show="isLyric" :disableBar="true" :currentTime="currentTime" :lyric="lyric" height="40px" ref="lyric"></PlayerLyric>

    <!-- 歌曲列表 -->
    <transition name="player-side">
      <PlayerList v-show="isGedan" :musicList="musicList"></PlayerList>
    </transition>

    <!-- 歌词全景 -->
    <transition name="player-pure-side">
      <PlayerPure :song="playList[currentIndex]" :currentTime="currentTime" :lyric="lyric" v-show="isPure"></PlayerPure>
    </transition>

    <!-- 音频播放器 -->
    <audio ref="audio" autoplay :src="getSongSrc" :loop="schemaIndex === 2 ? true : false" @timeupdate="audioTimeUpdate()" @pause="musicPause()" @play="playLoad()" @ended="musicEnded()" @playing="musicPlaying()" @error="musicErr()"></audio>

    <!-- 控制音频播放开关 -->
    <div class="player_toggle">
      <div class="player_toggle_last" @click="lastMusic">
        <i class="player-icon iconfont icon--previous"></i>
      </div>
      <div class="player_totale_btn" @click="toggle">
        <i class="player-icon-type iconfont icon-bofang1" v-show="!isPlay"></i>
        <i class="player-icon-type iconfont icon-zanting" v-show="isPlay"></i>
      </div>
      <div class="player_toggle_next" @click="nextMusic">
        <i class="player-icon iconfont icon-next"></i>
      </div>
    </div>

    <!-- 音频进度条 -->
    <div class="player_progress">
      <div class="player_progress_count_time">{{ getCurrentTime }}</div>
      <div class="player_progress_main">
        <b-progress :percent.sync="percent" :stroke-width="4" show-thumb hover-show-thumb allow-click allow-drag is-active :disable-transition="currentTime == 0" @click="handleAudioProgress" @dragend="handleAudioDragend" @dragbegin="handleAudioDragBegin" />
      </div>
      <div class="player_progress_time">{{ getDurationTime }}</div>
    </div>

    <!-- 音量进度条 -->
    <div class="player_volume">
      <div class="player_volume_icon" @click="toggleVolumn">
        <i class="player-small-icon iconfont icon-V" v-show="!isVolume" />
        <i class="player-small-icon iconfont icon-jingyin" v-show="isVolume" />
      </div>
      <div class="player_volume_main">
        <b-progress :percent.sync="volumnPercent" :stroke-width="3" show-thumb hover-show-thumb allow-click allow-drag is-active @click="handleVolumn" @dragend="handleVolumn" />
      </div>
    </div>

    <!-- 工具栏 -->
    <div class="player_tool">
      <div class="player-tool-schema" @click="toggleSchema()">
        <a href="#" title="顺序播放" v-show="schemaIndex == 0"><i class="player-small-icon iconfont icon-shunxu" /></a>
        <a href="#" title="随机播放" v-show="schemaIndex == 1"><i class="player-small-icon iconfont icon-suiji" /></a>
        <a href="#" title="单曲播放" v-show="schemaIndex == 2"><i class="player-small-icon iconfont icon-danqu" /></a>
      </div>
      <div class="player-tool-lyric" @click="toggleLyric">
        <a href="#" title="歌词"><i class="player-small-icon iconfont icon-lyric" :class="{ toggleLyric: isLyric === true }" /></a>
      </div>
      <div class="player-tool-list" @click="toggleMusicList">
        <a href="#" title="歌单"><i class="player-small-icon iconfont icon-gedan" :class="{ toggleLyric: isGedan === true }" /></a>
      </div>
    </div>
  </div>
</template>

<script>
import { _getLyric } from '../network/detail'
import { formatDate } from '../utils/formatDate'
import PlayerCover from './Player-cover.vue'
import PlayerLyric from './Player-lyric.vue'
import PlayerList from './Player-list.vue'
import PlayerPure from './Player-pure.vue'
export default {
  name: 'Player',
  components: { PlayerCover, PlayerLyric, PlayerList, PlayerPure },
  data() {
    return {
      percent: 0, // 音乐进度条百分比初始化
      volumnPercent: 100, // 音量进度条百分比
      schemaIndex: 0, // 乐播放方式--0:顺序、1：随机、2：单曲
      isPlay: false, // 切换是否暂停播放
      isVolume: false, // 切换是否静音
      isLyric: false, // 点击切换歌词图标颜色
      isGedan: false, // 点击切换歌单图标颜色
      isMusicDrag: false, // 音乐进度条是否正在拖拽
      preVolumnPercent: 0, // 在设置音量切换时暂时保存之前音量百分比
      id: null, // 歌曲ID
      musicList: null, // 歌单信息
      playList: [], // 播放列表
      currentIndex: 0, // 当前播放音乐
      currentTime: null, // 当前歌曲多长时间
      duration: 0, // 音乐总时间
      lyric: null, // 获取歌词
      isPure: false // 显示歌词全景
    }
  },
  computed: {
    /** 获取歌词播放地址 */
    getSongSrc() {
      return (this.playList[this.currentIndex] && this.playList[this.currentIndex].src) || ''
    },
    // 当前播放时间
    getCurrentTime() {
      return formatDate(new Date(this.currentTime * 1000), 'mm:ss') || '00:00'
    },
    getDurationTime() {
      return formatDate(new Date(this.duration * 1000), 'mm:ss') || '00:00'
    }
  },
  mounted() {
    /* * list是音乐列表,index是播放的音乐在列表中的位置,path是当前播放音乐的路径，musicList是歌单信息,ID是歌曲唯一的标志 */
    this.$bus.$on('playMusic', (playList, index, musicList, id) => {
      this.id = id
      this.musicList = musicList
      // 初始化播放列表
      this.playList = []
      // 对playList 进行处理
      let transferList = []
      // 过滤没有音乐地址的歌曲
      transferList = playList.filter((item) => {
        return item.src
      })
      // 对数组进行排序
      this.playList = transferList.sort((a, b) => {
        return a.index - b.index
      })

      this.setCurrentIndex(index)
    })
    this.$bus.$on('playMusicListItem', (index) => {
      this.setCurrentIndex(index)
    })
  },
  methods: {
    /** 返回当前的播放时间 */
    audioTimeUpdate() {
      if (this.$refs.audio !== null) {
        // 获取currentTime
        this.currentTime = this.$refs.audio.currentTime
        /*
        计算音乐播放进度百分比
        */
        if (!this.isMusicDrag) {
          this.percent = (this.currentTime / this.duration) * 100
        }
      }
    },
    /** 对播放暂停进行监视 */
    musicPause() {
      this.isPlay = false
      // if (this.$refs.player !== null) this.$refs.player.isPlay = false
    },

    // 监听音乐加载
    async playLoad() {
      this.duration = this.$refs.audio.duration
      const res = await _getLyric(this.playList[this.currentIndex].id)
      this.lyric = (res.data.lrc && res.data.lrc.lyric) || '暂无歌词'
    },

    // 监听音乐一开始播放
    musicPlaying() {
      this.isPlay = true
      this.$bus.$emit('Playing', this.playList[this.currentIndex].index, this.playList[this.currentIndex].name, this.id)
      // if (this.$refs.player != null) this.$refs.player.isPlay = true
    },

    /** 监听音乐播放结束、并判断播放方式 */
    musicEnded() {
      console.log('end', this.schemaIndex)
      switch (this.schemaIndex) {
        case 0: // 循环播放
          // this.currentIndex >= this.playList.length - 1 ? 0 : this.currentIndex++
          if (this.currentIndex >= this.playList.length - 1) {
            return 0
          } else {
            this.currentIndex++
          }
          break
        case 1: // 随机播放
          this.currentIndex = Math.floor(Math.random() * this.playList.length)
          break
        case 2: // 单曲循环
          // eslint-disable-next-line no-self-assign
          this.currentIndex = this.currentIndex
          break
      }
    },

    // 音乐报错了，查出了
    musicErr() {
      this.$Toast.error('当前音频不可用')
      this.currentIndex++
    },

    // 是否暂停播放
    toggle() {
      this.isPlay = !this.isPlay
      if (this.isPlay && this.$refs.audio.readyState === 4) {
        this.$refs.audio.play()
      } else {
        this.$refs.audio.pause()
      }
    },

    // 设置要播放哪首歌
    setCurrentIndex(index) {
      this.playList.forEach((item) => {
        if (item.index === index) {
          this.currentIndex = index
        }
      })
    },
    // 加载上下一首歌
    lastMusic() {
      if (this.playList === null) return
      if (this.currentIndex <= 0) {
        this.currentIndex = this.playList.length - 1
      } else {
        this.currentIndex--
      }
      this.$refs.audio.src = this.playList[this.currentIndex].src
    },
    nextMusic() {
      if (this.playList === null) return
      if (this.currentIndex >= this.playList.length - 1) this.currentIndex = 0
      else this.currentIndex++
    },

    // 处理音量进度条点击和拖拽事件
    handleVolumn() {
      this.setVolume()
    },
    // 设置浏览器音量
    setVolume() {
      if (this.$refs.audio) this.$refs.audio.volume = this.volumnPercent / 100
    },
    // 切换音量 静音-恢复
    toggleVolumn() {
      this.isVolume = !this.isVolume
      if (this.isVolume) {
        this.preVolumnPercent = this.volumnPercent
        this.$refs.audio.volume = 0.0
        this.volumnPercent = 0
      } else {
        this.$refs.audio.volume = this.preVolumnPercent / 100
        this.volumnPercent = this.preVolumnPercent
      }
    },
    // 处理音频进度条点击事件
    handleAudioProgress() {
      this.setMusicCurrent()
    },
    // 音乐进度条正在拖拽
    handleAudioDragend() {
      this.isMusicDrag = true
      this.setMusicCurrent()
    },
    // 音乐进度条拖拽结束
    handleAudioDragBegin() {
      this.isMusicDrag = false
    },
    /** 设置音乐进度
     * @param 设置的百分比
     */
    setMusicCurrent() {
      this.$refs.audio.currentTime = (this.percent / 100) * this.$refs.audio.duration
      this.percent = (this.$refs.audio.currentTime / this.$refs.audio.duration) * 100
    },
    // 1
    toggleLyric() {
      this.isLyric = !this.isLyric
    },
    // 2
    toggleMusicList() {
      this.isGedan = !this.isGedan
    },
    // 播放方式
    toggleSchema() {
      if (this.schemaIndex >= 2) this.schemaIndex = 0
      this.schemaIndex++
    }
  }
}
</script>

<style lang="less" scoped>
.player_class {
  display: flex;
  .player_toggle {
    width: 14%;
    height: 60px;
    padding-left: 10px;
    display: flex;
    align-items: center;
    .player_toggle_last {
      width: 20%;
    }
    .player_totale_btn {
      width: 50%;
      display: flex;
      justify-content: center;
    }
    .player-icon {
      font-size: 26px;
    }
    .player_toggle_next {
      width: 20%;
      display: flex;
      justify-content: flex-end;
    }
    .player-icon-type {
      font-size: 32px;
    }
  }
  .player_progress {
    width: 58%;
    height: 60px;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 0 20px;
    .player_progress_count_time {
    }
    .player_progress_main {
      padding-left: 30px;
      padding-right: 20px;
      width: 90%;
    }
    .player_progress_time {
    }
  }
  .player_volume {
    width: 14%;
    height: 60px;
    display: flex;
    align-items: center;
    .player_volume_icon {
      width: 40px;
      padding-right: 20px;
      .player-small-icon {
        font-size: 20px;
      }
    }
    .player_volume_main {
      width: 120px;
    }
  }
  .player_tool {
    width: 14%;
    height: 60px;
    display: flex;
    justify-content: center;
    align-items: center;
    padding-right: 20px;
    div {
      width: 33.33%;
      a {
        text-decoration: none;
        color: #000;
        font-size: 26px;
      }
    }
    .toggleLyric {
      color: #2d8cf0;
    }
  }
  .player_lyric {
    position: absolute;
    left: 0;
    top: -60px;
    width: 100%;
  }
  .player-side-enter-active {
    animation: slideInRight var(--animation-base-time);
  }
  .player-side-leave-active {
    animation: slideInRight var(--animation-base-time) reverse;
  }
  .player-pure-side-enter-active {
    animation: slideInUp var(--animation-base-time);
  }
  .player-pure-side-leave-active {
    animation: slideInUp var(--animation-base-time) reverse;
  }
}
</style>
